﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Threading;
using System.IO;

public partial class MaterialDetailReport : System.Web.UI.Page, INormalReport
{
    const string QueryWhere = "MaterialDetailReport";
    uMESZZBusiness bll = new uMESZZBusiness();
    
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：进料明细报表";
        master.strTitle = "进料明细报表";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        if (!IsPostBack)
        {
            BindFactory();
            BindFamily();
            BindTeam();
            BindStation();
        }
    }

    #region 绑定车间数据
    private void BindFactory()
    {
        System.Data.DataTable dt = bll.GetFactory();
        ddlFactory.DataSource = dt;
        ddlFactory.DataTextField = "FactoryName";
        ddlFactory.DataValueField = "FactoryID";
        ddlFactory.DataBind();
        ddlFactory.Items.Insert(0, new ListItem("", ""));
    }
    #endregion

    #region 绑定车型数据
    private void BindFamily()
    {
        System.Data.DataTable dt = bll.GetFamily();
        ddlFamily.DataSource = dt;
        ddlFamily.DataTextField = "ProductFamilyName";
        ddlFamily.DataValueField = "ProductFamilyID";
        ddlFamily.DataBind();
        ddlFamily.Items.Insert(0, new ListItem("", ""));
    }
    #endregion

    #region 绑定班组数据
    private void BindTeam()
    {
        System.Data.DataTable dt = bll.GetTeam();
        ddlTeam.DataSource = dt;
        ddlTeam.DataTextField = "TeamName";
        ddlTeam.DataValueField = "TeamID";
        ddlTeam.DataBind();
        ddlTeam.Items.Insert(0, new ListItem("", ""));
    }
    #endregion

    #region 绑定配送地点数据
    private void BindStation()
    {
        System.Data.DataTable dt = bll.GetStation();
        ddlStation.DataSource = dt;
        ddlStation.DataTextField = "WorkStationName";
        ddlStation.DataValueField = "WorkStationID";
        ddlStation.DataBind();
        ddlStation.Items.Insert(0, new ListItem("", ""));
    }
    #endregion

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        
    }
    #endregion

    #region 查询
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //
    }

    public void QueryData(string[] query)
    {
        uMESPagingDataDTO result = bll.GetSourceData_D(query, Convert.ToInt32(this.txtCurrentPage.Text), 15);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        this.txtTotalPage.Text = result.PageCount;
        if (result.RowCount == "0")
        {
            this.txtCurrentPage.Text = "0";
        }
        lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
        this.txtPage.Text = this.txtCurrentPage.Text;
    }

    public void ResetQuery()
    {
        Session[QueryWhere] = "";
        ddlFamily.SelectedValue = string.Empty;
        ddlFactory.SelectedValue = string.Empty;
        ddlTeam.SelectedValue = string.Empty;
        txtProcessNo.Text = string.Empty;
        ddlStation.SelectedValue = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }

    public string[] GetQuery()
    {
        string strProductFamilyID = ddlFamily.SelectedValue;
        string strFactoryID = ddlFactory.SelectedValue;
        string strTeamID = ddlTeam.SelectedValue;
        string strWorkStationID = ddlStation.SelectedValue;
        string strProcessNo = txtProcessNo.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();
        
        string[] result = new string[7];
        result[0] = strProductFamilyID;
        result[1] = strFactoryID;
        result[2] = strTeamID;
        result[3] = strWorkStationID;
        result[4] = strProcessNo;
        result[5] = strStartDate;
        result[6] = strEndDate;

        return result;
    }
    #endregion

    #region Excel导出
    protected void btnExport_Click(object sender, EventArgs e)
    {
        string[] query = GetQuery();
        System.Data.DataTable DT = bll.GetAllDataForOutExcel_D(query);
        if (DT.Rows.Count == 0)
        {
            Response.Write("<script>alert('未查询，不能导出空数据！')</script>");
            return;
        }
        System.Data.DataTable dtTemp = DT;

        System.Data.DataTable dtResult = new System.Data.DataTable();
        //dtResult.Columns.Add("RN");
        dtResult.Columns.Add("ProductFamilyName");
        dtResult.Columns.Add("FactoryName");
        dtResult.Columns.Add("TeamName");
        dtResult.Columns.Add("WorkStationName");
        dtResult.Columns.Add("ProcessNo");
        dtResult.Columns.Add("ProductName");
        //dtResult.Columns.Add("ProductRevision");
        dtResult.Columns.Add("Description");
        dtResult.Columns.Add("Qty");
        dtResult.Columns.Add("CreateDate");

        //dtResult.Columns["RN"].Caption = "序号";
        dtResult.Columns["ProductFamilyName"].Caption = "车型";
        dtResult.Columns["FactoryName"].Caption = "责任单位";
        dtResult.Columns["TeamName"].Caption = "班组";
        dtResult.Columns["WorkStationName"].Caption = "配送地点";
        dtResult.Columns["ProcessNo"].Caption = "令号";
        dtResult.Columns["ProductName"].Caption = "物料图号";
        //dtResult.Columns["ProductRevision"].Caption = "版本";
        dtResult.Columns["Description"].Caption = "名称";
        dtResult.Columns["Qty"].Caption = "配送数量";
        dtResult.Columns["CreateDate"].Caption = "配送时间";

        uMESCommonBusiness rep = new uMESCommonBusiness();
        for (int i = 0; i <= dtTemp.Rows.Count - 1; i++)
        {
            DataRow dr = dtResult.NewRow();
            //dr["RN"] = i + 1;
            dr["ProductFamilyName"] = dtTemp.Rows[i]["ProductFamilyName"].ToString();
            dr["FactoryName"] = dtTemp.Rows[i]["FactoryName"].ToString();
            dr["TeamName"] = dtTemp.Rows[i]["TeamName"].ToString();
            dr["WorkStationName"] = dtTemp.Rows[i]["WorkStationName"].ToString();
            dr["ProcessNo"] = dtTemp.Rows[i]["ProcessNo"].ToString();
            dr["ProductName"] = dtTemp.Rows[i]["ProductName"].ToString();
            //dr["ProductRevision"] = dtTemp.Rows[i]["ProductRevision"].ToString();
            dr["Description"] = dtTemp.Rows[i]["Description"].ToString();
            dr["Qty"] = dtTemp.Rows[i]["Qty"].ToString();
            dr["CreateDate"] = dtTemp.Rows[i]["CreateDate"].ToString();

            dtResult.Rows.Add(dr);
        }
        string content = getExcelContent(dtResult, "进料明细报表");
        ExportToExcel("进料明细报表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", content, "");
    }


    public void ExportToExcel(string filename, string content, string cssText)
    {
        var res = HttpContext.Current.Response;
        content = String.Format("<style type='text/css'>{0}</style>{1}", cssText, content);

        res.Clear();
        res.Buffer = true;
        res.Charset = "UTF-8";
        filename = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename)));
        res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
        res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        res.ContentType = "application/ms-excel;charset=UTF-8";
        // res.ContentType = "application/octet-stream";
        res.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
        res.Write(content);
        res.Flush();
        res.End();
    }


    public string getExcelContent(System.Data.DataTable dt, string strTitle)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("<table borderColor='black' border='1'>");
        sb.AppendFormat("<thead><tr><th colSpan='{0}' bgColor='#ccfefe'>", dt.Columns.Count);
        sb.AppendFormat("{0}", strTitle);
        sb.Append("</th></tr><tr>");
        foreach (DataColumn dc in dt.Columns)
        {
            sb.AppendFormat("<th bgColor='#ccfefe'>{0}</th>", dc.Caption);
        }
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");
        foreach (DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            foreach (object str in dr.ItemArray)
            {
                if (str.GetType().Name == "String")
                {
                    sb.AppendFormat("<td>{0}</td>", str);
                }
                else if (str.GetType().Name == "Decimal")
                {
                    sb.AppendFormat("<td>{0:D2}</td>", str.ToString());
                }
                else if (str.GetType().Name == "Double")
                {
                    sb.AppendFormat("<td>{0:D2}</td>", str.ToString());
                }
                else if (str.GetType().Name == "Int32")
                {
                    sb.AppendFormat("<td>{0}</td>", str.ToString());
                }
                else if (str.GetType().Name == "DateTime")
                {
                    sb.AppendFormat("<td>{0}</td>", str.ToString());
                }
                else if (str.GetType().Name == "DBNull")
                {
                    sb.AppendFormat("<td></td>");
                }
                else
                {
                    sb.AppendFormat("<td>{0}</td>", str.ToString());
                }
            }
            sb.Append("</tr>");
        }
        sb.Append("</tbody></table>");
        return sb.ToString();
    }


    #endregion
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

    }
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }

    protected void btnTestExport_Click(object sender, EventArgs e)
    {
        DataTable DT = bll.GetAllDataForOutExcel_D(GetQuery());
        WriteExcel(DT, "C:/MESShopfloor/daMESReport/ExportFile/test.xls");
    }

    public void WriteExcel(DataTable DT, string path)
    {
        try
        {
            long totalCount = DT.Rows.Count;
            //writeMessage += "共有: " + totalCount + "条数据";
            Thread.Sleep(1000);
            //long rowRead = 0;
            //float percent = 0;

            StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312"));
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < DT.Columns.Count; k++)
            {
                sb.Append(DT.Columns[k].ColumnName.ToString() + "\t");
            }
            sb.Append(Environment.NewLine);

            for (int i = 0; i < DT.Rows.Count; i++)
            {
                //rowRead++;
                //percent = ((float)(100 * rowRead)) / totalCount;
                //  Pbar.Maximum = (int)totalCount;
                //  Pbar.Value = (int)rowRead;
                //writeMessage += "\r\n" + "正在写入[" + percent.ToString("0.00") + "%]...的数据";
                //System.Windows.Forms.Application.DoEvents();

                for (int j = 0; j < DT.Columns.Count; j++)
                {
                    sb.Append(DT.Rows[i][j].ToString() + "\t");
                }
                sb.Append(Environment.NewLine);
            }
            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
            //MessageBox.Show("已经生成指定Excel文件!");

            Response.Write("<script>open('ExportFile/test.xls','newwindow');</script>");
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "');</script>");
        }
    }

    Dictionary<string, string> INormalReport.GetQuery()
    {
        throw new NotImplementedException();
    }

    public void QueryData(Dictionary<string, string> query)
    {
        throw new NotImplementedException();
    }
}